<template>
  <div class="box">
    <div class="fixed">
      <van-nav-bar :fixed="true" title="城市列表" left-arrow @click-left="$router.go(-1)" />
    </div>
    <van-index-bar :index-list="indexList" :sticky="true" :z-index="0" :sticky-offset-top="60">
      <van-index-anchor index="#">当前城市</van-index-anchor>
      <van-cell :title="city" />
      <van-index-anchor index="热">热门城市</van-index-anchor>
      <van-cell v-for="(hotItem , index) in hotArray" :key="index" :title="hotItem.label" @click="clickfn($event)"/>
      <!-- A-Z 城市 -->
      <template v-for="(item, index) in array">
        <van-index-anchor :key="list[index]" :index="list[index]">{{list[index]}}</van-index-anchor>
        <template v-if="item.length">
          <van-cell v-for="(elment) in item" :key="elment.value" :title="elment.label"/>
        </template>
        <template  v-if="!item.length">
          <van-cell :key="index" title="暂无城市" />
        </template>
      </template>
    </van-index-bar>
  </div>
</template>

<script>
import { City, HotCity } from '@/api/other'
import { setStr, getStr } from '@/utils/storage'
export default {
  data () {
    return {
      indexList: ['#', '热', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ],
      list: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ],
      array: [],
      hotArray: [],
      city: getStr() ? JSON.parse(getStr()).label : '上海'
    }
  },
  async created () {
    const res = await HotCity()
    const { body } = await City()
    console.log(body)
    console.log(res.body)
    this.hotArray = res.body
    this.list.forEach((str) => {
      this.array.push(
        body.filter((item) => item.short[0].toUpperCase() === str)
      )
    })
  },
  methods: {
    clickfn (e) {
      console.log(e.target.innerText)
      this.city = e.target.innerText
      const dz = this.hotArray.find(item => item.label === e.target.innerText)
      setStr(JSON.stringify(dz))
      this.$router.go(-1)
    }
  }
}
</script>

<style>
.fixed {
  height: 60px;
}
.van-index-bar__index {
  padding-top: 5px;
}
</style>
